<template>
  <div class="document-list-container">    
    <div class="list-noData" v-if="value.list && value.list.length <= 0">暂无数据</div>
    <el-checkbox-group
      v-else
      v-model="checkList"
      class="list-content"
      ref='lisrContent'
      :class="{
        noCheckbox
      }"
      @change="selectionChange">
      <template v-for="item in value.list">
        <div :key="item.id" class="list-item">
          <el-checkbox
            :label="item.id"
            v-if="!noCheckbox"
            class="list-checkbox"
            :class="id == item.id ? 'choosed-item' : ''">
            {{''}}
          </el-checkbox>
          <div class="list-item-main" @click="toDetail(item)">
            <div class="item-top">
              <i class="iconfont icon-fd-attachment" v-if="item.hasAttachment"></i>
              <h3>
                <p class="item-title" ref="title" v-html="item.handleTitle">
                  {{item.title}}
                </p>
                <div class="type" v-if="item.label && item.label.length > 0">
                  <!-- @click="handleTags(tag)" -->
                  <el-tag
                    class="search-tag"
                    v-for="(tag,index) in (item.label || []).slice(0, 5)"
                    :key="index">{{tag}}
                  </el-tag>
                </div>
              </h3>
              <!-- 草稿箱显示审核状态 -->
              <el-popover
                width="200"
                trigger="hover"
                placement="top"
                popper-class="more-approve"
                :content="formatApprovers(item.wikiApproveUsers)"
                :disabled="item.wikiApproveUsers && item.wikiApproveUsers.length == 1"
              >
              <div class="approver" v-if="item.examineState == 1 && item.wikiApproveUsers && item.wikiApproveUsers.length"  slot="reference" >
                <template v-if="isOpenData && item.wikiApproveUsers[0].staffId">
                  {{$t('common.wiki.await')}}<open-data type='userName' :openid="item.wikiApproveUsers[0].staffId"></open-data> <span>{{item.wikiApproveUsers[0].length > 1? $t('common.wiki.wait', {total: item.wikiApproveUsers.length}) :$t('common.base.approve')}}</span>
                </template>
                <template v-else>
                  <span v-if="item.wikiApproveUsers.length > 1">
                    {{$t('common.wiki.approver',{name: item.wikiApproveUsers[0].displayName, total: item.wikiApproveUsers.length})}}
                  </span>
                  <span v-else>
                    {{$t('common.wiki.await')}}{{ item.wikiApproveUsers[0].displayName }}{{$t('common.base.approve')}}
                  </span>
                </template>
              </div>
            </el-popover>
              <el-tag class="review-tag" v-if="item.examineState && item.examineState == 2" :type="item.examineState == 1 ? '' : 'danger'">{{item.examineState == 1 ? $t('common.base.usualStatus.toBeReviewed') : $t('common.base.usualStatus.rejected')}}</el-tag>
            </div>

            <div :class="['item-cursor',`${item.examineState === null ? 'item-cursor-margin' : ''}`]">
              <div class="item-info">
                <span class="name">
                  <template v-if="isOpenData">
                    <open-data type="userName" :openid="item.createUserStaffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.createUserName}}
                  </template>
                </span>
                <span class="time">{{$t('wiki.list.list.label1')}}：{{item.createTime | fmt_datehour}}</span>
                
                <span class="wikiNumber">
                  {{ $t('wiki.detail.approveDialog.label1') }}：
                  {{ item.wikiNumber }}
                </span>
                
                <!-- <span class="type">{{item.type}}</span> -->
              </div>

              <!-- 故障库信息 Start -->
              <div class="item-info" v-if="item.wikiType === 1">
                <p class="FaultList"><label class="FaultName">{{$t('wiki.list.list.label2')}}：</label><span>{{ item.productTypeList && item.productTypeList.map(item=>item.hierarchyName).join(',') }}</span></p>
                <p class="FaultList"><label class="FaultName">{{$t('wiki.list.list.label3')}}：</label><span>{{item.faultPerformance}}</span></p>
                <p class="FaultList"><label class="FaultName">{{$t('wiki.list.list.label4')}}：</label><span>{{item.faultReason}}</span></p>
                <p class="FaultList"><label class="FaultName">{{$t('wiki.list.list.label5')}}：</label><span v-html="item.handleContent"></span></p>
                <p class="FaultList"><label class="FaultName">{{$t('wiki.list.list.label6')}}：</label><span v-if="item.repairCostBegin || item.repairCostEnd">{{item.repairCostBegin}} <span v-if="item.repairCostBegin && item.repairCostEnd">~</span> {{item.repairCostEnd}}</span></p>
              </div>
              <!-- 故障库信息 End -->

              <p class="item-content" v-else ref="content" v-html="item.handleContent">{{item.content}}</p>
            </div>
            

            <div class="item-footer">

              <div class="status-view footer-left" v-if="item.examineState === null">
                <span
                  class="status-view-each canClick"
                  @click.stop="wikiLike(!item.like, item)">
                  <i
                    class="iconfont"
                    :class="{
                      'icon-dianzan': !item.like,
                      'icon-like-fill': item.like
                    }"></i>
                    <b>{{ item.likeTimes || 0 }}</b>
                  </span>
                <span
                  class="status-view-each">
                  <i class="iconfont icon-pinglun"></i>
                  <b>{{ item.commentTimes || 0 }}</b>
                </span>
                <span
                  @click.stop="wikiCollection(!item.collection, item)"
                  class="status-view-each canClick">
                  <i
                    class="iconfont"
                    :class="{
                      'icon-shoucang': !item.collection,
                      'icon-yishoucang': item.collection
                    }"></i>
                  <b>{{ item.collectionTimes || 0 }}</b>
                </span>
                <span
                  class="status-view-each">
                  <i class="iconfont icon-yuedu"></i>
                  <b>{{ item.readTimes || 0 }}</b>
                </span>
                <span class="status-view-each">
                  <i
                    class="iconfont"
                    :class="{
                      'icon-neibu': !item.allowShare,
                      'icon-unlock': item.allowShare
                    }"></i>
                  <b>{{!item.allowShare ? $t('common.base.inside') : $t('common.base.outside')}}</b>
                </span>
              </div>
              <!-- 我发布的显示权限、阅读量、分享 -->
              <div class="footer-right status-view" v-if="!item.isDraft">
                <!-- 我发布的显示分享 -->
                <!-- wikiShare -->
                <span class="share status-view-each canClick" @click.stop="wikiShare(item);trackEventHandler('share')" v-if="!item.isDraft && shareEnable">
                  <i class="iconfont icon-share icon-article-share"></i>
                  <b>{{$t('common.base.share')}}</b>
                </span>
                <!-- <span
                  class="status-view-each canClick"
                  v-if="!item.isDraft && allowEdit(item) && linkControl && isShowSelfServicePortal"
                  @click.stop="changeRelease(item);trackEventHandler('share')"
                >
                  <i
                    class="iconfont icon-quanzi icon-article-share"
                    :class="{
                      'active': item.circleState === 1
                    }">
                  </i>
                  <b>{{ item.circleState === 1 ? '取消发布' : '发布到自助门户企业圈子' }}</b>
                </span> -->
                <!-- <el-tooltip v-if="item.allowShare" effect="dark" :content="item.circleState == 1 ? '取消发布' : '发布到自助门户'" placement="bottom">
                  <span
                    class="status-view-each canClick"
                    v-if="!item.isDraft && allowEdit(item) && linkControl && isShowSelfServicePortal"
                    @click.stop="changeRelease(item);trackEventHandler('share')"
                  >
                    <i
                      class="iconfont icon-quanzi icon-article-share"
                      :class="{
                        'active': item.circleState === 1
                      }">
                    </i>
                    <b>{{ item.circleState === 1 ? '取消发布' : '发布到自助门户' }}</b>
                  </span>
                </el-tooltip> -->
                <!-- <span class="readNum status-view-each" v-if="item.circleState == 1 && linkControl && isShowSelfServicePortal">
                  <i class="iconfont icon-quanziguanli"></i>
                </span> -->
              </div>

            </div>

          </div>
        </div>
      </template>

    </el-checkbox-group>

  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import * as RepositoryApi from '@src/api/Repository';
import Clipboard from 'clipboard';
import { isShowSelfServicePortal } from '@shb-lib/version'
import { getRootWindow } from '@src/util/dom'

export default {
  name: 'list',
  props: {
    keyword: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: () => ({})
    },
    id: {
      type: String,
      default: ''
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
    noCheckbox: {
      type: Boolean,
      default: false
    },
    wikiShare: {
      type: Function
    },
    shareEnable: {
      type: Boolean,
      default: false
    },
    currentTreeActiveId: {},
    type: {
      type: String,
      default: ''
    },
    // 是否是故障库
    isFault: {
      type: Boolean,
      default: false
    },
  },
  computed:{
    // 联客商城灰度开关
    linkControl() {
      // return this.initData.openLinkC;
      const RootWindow = getRootWindow(window);
      return this.initData.openLinkC || RootWindow.grayAuth?.portal || false;
    },
    isShowSelfServicePortal() {
      return isShowSelfServicePortal()
    }
  },
  data () {
    return {
      isOpenData,
      total: 18,
      checkList: [],

      likeLoading: false,
      collectionLoading: false
    }
  },
  methods: {
    /**格式化人员 */
    formatApprovers (wikiApproveUsers) {
      return (wikiApproveUsers || []).map(obj => obj.displayName).join('，');
    },
    checkWiki(e, item) {
      let classList = e.target.classList || {}
      if (
        !classList?.contains('el-checkbox__inner')
        && !classList?.contains('el-checkbox__input')
        && !classList?.contains('el-checkbox__original')
      ) {
        e.preventDefault()
        // this.toDetail(item)
        return
      }
    },
    allowEdit (item) {
      return this.initData.userInfo.authorities.INFO_COMPILER
             || (item.createUser == this.initData.userInfo.userId && this.initData.userInfo.authorities.VIP_INFO_CREATE)
    },
    resetScrollTop () {
      this.$refs.lisrContent.scrollTop = 0;
    },
    // 点击标签成为搜索条件
    handleTags (tag) {
      this.$emit('tag', tag);
      trackEventHandler('tag')
    },

    // 跳转到详情页面
    toDetail (item) {
      // this.id = item.id;
      this.$emit('update:id', item.id);
      this.$emit('toDetail', item)
    },

    // TalkingData事件埋点
    trackEventHandler (type) {
      if (type === 'share') {
        window.TDAPP.onEvent('pc：知识库列表-分享事件');
        return;
      }
      if (type === 'reset') {
        window.TDAPP.onEvent('pc：知识库列表-点击标签搜索');
        return;
      }
    },

    wikiLike(ifLike, item) {
      if(this.likeLoading) return
      let fn = ifLike ? RepositoryApi.wikiLike : RepositoryApi.wikiCancelLike
      this.likeLoading = true
      fn({
        wikiId: item.id
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: ifLike ? this.$t('wiki.list.list.wikiLike.tips1') : this.$t('wiki.list.list.wikiLike.tips2'),
            type: "success"
          })
          this.$set(item, 'like', ifLike)
          this.getWikiData(item)
        } else {
          this.$platform.notification({
            title: res.message,
            type: "error",
          });
        }
      }).finally(() => {
        this.likeLoading = false
      })
    },
    wikiCollection(ifCollection, item) {
      if(this.collectionLoading) return
      let fn = ifCollection ? RepositoryApi.addCollection : RepositoryApi.cancelCollection
      this.collectionLoading = true
      fn({
        wikiId: item.id
      }).then(res => {
        if(res.code === 0) {
          this.$platform.notification({
            title: ifCollection ? this.$t('wiki.list.list.wikiCollection.tips1') : this.$t('wiki.list.list.wikiCollection.tips2'),
            type: "success"
          })
          this.$set(item, 'collection', ifCollection)
          this.getWikiData(item)
          if (this.currentTreeActiveId === 'collection') {
            this.$emit('reloadList')
          }
        } else {
          this.$platform.notification({
            title: res.message,
            type: "error",
          });
        }
      }).finally(() => {
        this.collectionLoading = false
      })
    },

    getWikiData(item) {
      RepositoryApi.getWikiData({
        id: item.id
      }).then(res => {
        if(res.code === 0) {
          Object.assign(item, res.result?.times)
          // this.wikiCountData = res.result?.times || {}
          // this.wikiStateData = res.result?.state || {}
        } else {
          this.$platform.notification({
            title: res.message,
            type: "error",
          })
        }
      })
    },

    changeRelease(item) {
      this.$confirm(
        item.circleState === 1 ? this.$t('wiki.list.list.changeRelease.tips1') : this.$t('wiki.list.list.changeRelease.tips2'),
        item.circleState === 1 ? this.$t('common.base.toast') : this.$t('wiki.list.list.changeRelease.tips3'),
        {
          cconfirmButtonText: this.$t('common.base.confirm'),
          cancelButtonText: this.$t('common.base.cancel'),
        }
      ).then(() => {
        RepositoryApi.releaseCircle({
          id: item.id,
          circleState: 1 - item.circleState * 1,
        }).then((res) => {
          if (res.code == 0) {
            item.circleState = 1 - item.circleState * 1;
            this.$message({
              message: item.circleState == 1 ? this.$t('wiki.list.list.changeRelease.tips4') : this.$t('wiki.list.list.changeRelease.tips5'),
              duration: 1500,
              type: "success",
            });
            this.$set(item, circleState, item.circleState * 1)
          } else {
            this.$message({
              message: res.message,
              duration: 1500,
              type: "error",
            });
          }
        });
      }).catch(() => {});
    },

    selectionChange(arr) {
      this.$emit('selectChange', this.value.list.filter(item => arr.includes(item.id)))
    }
  }
}
</script>

<style lang="scss">
.FaultList{
  font-size: 14px;
  margin-bottom: 8px;
  span{
    color: #595959;
    white-space: normal;
  }
}
.document-list-container {
  display: flex;
  flex-direction: column;

  background: #fff;
  height: 100%;
  overflow: hidden;

  .list-content {
    overflow: auto;
    flex: 1;

    .list-noData {
      line-height: 40px;
      text-align: center;
      color: #909399;
    }
  }

  .list-item {
    width: 100%;
    overflow: hidden;
    padding: 16px;
    border-bottom: 1px solid #E5E6E5;
    margin-right: 0;
    display: flex;
    align-items: baseline;
    /*height: 156px;*/
    overflow: hidden;

    .item-top {
      font-size: 0;
      display: flex;
      height: 22px;
      line-height: 22px;
      margin-bottom: 8px;

      .icon-fd-attachment {
        vertical-align: middle;
        font-size: 12px;
        margin-right: 5px;
      }

      .item-title {
        margin: 0;
        vertical-align: middle;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        cursor: pointer;
      }

      .share {
        width: 20px;
        height: 20px;
        line-height: 20px;

        cursor: pointer;

        .icon-article-share {
          font-size: 16px;
          color: $color-primary-light-6;
        }
      }

      .review-tag {
        vertical-align: middle;
        margin-left: 24px;
      }
      .approver {
        font-size: 14px;
        color: $color-warning;
      }
    }
    
    .item-cursor {
      cursor: pointer;
      flex: 1;
      overflow: hidden;
      display: inline-flex;
      flex-direction: column;

      .item-info {
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        font-weight: 400;
        color: #8C8C8C;
        font-size: 0;
        margin-bottom: 8px;
        flex-shrink: 0;
        span {
          font-size: 12px;
          margin-right: 4px;
        }
      }

      .item-content {
        margin: 0;

        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        word-break: break-all;
        white-space: normal;

        font-size: 14px;
        font-weight: 400;
        color: #595959;
        line-height: 20px;
      }
    }
    .item-cursor-margin {
      margin: 0 0 12px;
    }

    .item-footer {
      display: flex;
      justify-content: space-between;
      font-size: 12px;

      .footer-right {
        flex: 1;
        text-align: right;

        .icon-permission {
          font-size: 14px;
          color: #B0BCC3;
          margin-right: 3px;
        }

        .readNum {

          .icon-yanjing {
            font-size: 8px;
            color: #B0BCC3;
            margin-left: 8px;
          }

          .icon-quanziguanli{
            font-size: 8px;
            color: #38A6A6;
            margin-left: 8px;
          }

          // span {
          //   display: inline-block;
          //   padding-left: 5px;
          // }
        }
      }

      .type {
        font-size: 0;

        .icon-tags {
          vertical-align: middle;
          font-size: 16px;
          color: #B0BCC3;
        }

        .search-tag {
          max-width: 62px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;

          margin-right: 4px;
          border: none;
          @include backgroundColorPrimaryLight9();
          color: #606266;
          vertical-align: middle;
          cursor: pointer;
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
  ::v-deep .el-checkbox__label {
    flex: 1;
    overflow: hidden;
  }
  .document-list-container {
    .list-item {
      .item-title {
        font-size: 16px;
        font-weight: bold;
        color: #262626;
        line-height: 22px;
        width: auto;
      }

      &:hover {
        background: #FAFAFA;
        .item-title {
          color: $color-primary-light-6;
          ::v-deep span {
            color: $color-primary-light-6 !important;
          }
        }
      }
    }
    .list-item-main {
      flex: 1;
      overflow: hidden;
    }
    .item-top {
      justify-content: space-between;
      h3 {
        display: flex;
        margin-bottom: 0;
        overflow: hidden;
        flex: 1;
        p {
          max-width: 50%;
        }
      }
      .search-tag {
        height: 22px;
        background: $color-primary-light-1;
        border-radius: 4px;
        border: 1px solid $color-primary-light-1;
        font-size: 12px;
        font-weight: 400;
        color: $color-primary-light-6;
        margin-left: 16px;
        &+.search-tag {
          margin-left: 4px;
        }
      }
    }
  }
  .status-view {
    &-each {
      color: #595959;
      margin-right: 24px;
      font-size: 0;
      line-height: 20px;
      display: inline-flex;
      align-items: baseline;
    }
    .canClick {
      cursor: pointer;
    }
    b {
      font-size: 14px;
      font-weight: 400;
      vertical-align: middle;
    }
    .iconfont {
      font-size: 16px;
      font-weight: 400;
      vertical-align: middle;
      &:before {
        margin-right: 4px;
      }
    }
    .icon-like-fill {
      color: #ff7043;
    }
    .icon-yishoucang {
      color: $color-primary-light-6;
    }
  }
  .icon-quanzi.active {
    color: $color-primary-light-6;
  }

  .noCheckbox {
    .list-item-main {
      margin-left: 24px;
      display: flex;
      flex-direction: column;
      height: 100%;
    }
  }

  ::v-deep .choose-item {
    width: 24px;
    .el-checkbox__inner {
      width: 16px;
      height: 16px;
    }
  }
  .more-approve {
    padding: 10px 12px;
  }
</style>
